package com.incar.chuxing.utils.zxing.android;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.incar.chuxing.R;
import com.incar.chuxing.base.BaseScanActivity;
import com.incar.chuxing.utils.AppManager;
import com.incar.chuxing.utils.Constants;
import com.incar.chuxing.utils.Dialogs.InCarDialog;
import com.incar.chuxing.utils.zxing.camera.CameraManager;
import com.incar.chuxing.utils.zxing.view.ViewfinderView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import com.google.zxing.Result;
import com.incar.chuxing.utils.StatusBarUtil;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;

/**
 * 这个activity打开相机，在后台线程做常规的扫描；它绘制了一个结果view来帮助正确地显示条形码，在扫描的时候显示反馈信息，
 * 然后在扫描成功的时候覆盖扫描结果
 */
public final class CaptureActivity extends BaseScanActivity implements
        SurfaceHolder.Callback {
    private static final String TAG = CaptureActivity.class.getSimpleName();

    // 相机控制
    private CameraManager cameraManager;
    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private boolean hasSurface;
    private SurfaceHolder holder;
    @SuppressWarnings("unused")
    private IntentSource source;
    private Collection<BarcodeFormat> decodeFormats;
    private Map<DecodeHintType, ?> decodeHints;
    private String characterSet;
    // 电量控制
    private InactivityTimer inactivityTimer;
    // 声音、震动控制
    private BeepManager beepManager;

    private ImageView imageButton_back;

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public CameraManager getCameraManager() {
        return cameraManager;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }

    private boolean isLightOn = false;
    private ImageView iv_scan_light;
    private LinearLayout lin_scan_light;
    private LinearLayout lin_scan_input;
    private TextView tv_scan_light;

    /**
     * OnCreate中初始化一些辅助类，如InactivityTimer（休眠）、Beep（声音）以及AmbientLight（闪光灯）
     */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        // 保持Activity处于唤醒状态
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.capture);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.black_pure), 0,false);
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
        beepManager = new BeepManager(this);
        AppManager.getAppManager().addActivity(this);
        initView();
    }

    private void initView() {
        imageButton_back = (ImageView) findViewById(R.id.capture_imageview_back);
        imageButton_back.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView capture_title = (TextView) findViewById(R.id.capture_title);
        Intent intent = getIntent();
        capture_title.setText(intent.getStringExtra("title"));
        iv_scan_light = (ImageView) findViewById(R.id.iv_scan_light);
        tv_scan_light = (TextView) findViewById(R.id.tv_scan_light);
        lin_scan_light = (LinearLayout) findViewById(R.id.lin_scan_light);
        lin_scan_light.setOnClickListener(new View.OnClickListener() {
            //监听闪光灯按钮
            @Override
            public void onClick(View v) {
                cameraManager.flashHandler();
                if (!isLightOn) {
                    iv_scan_light.setImageDrawable(getResources().getDrawable(R.drawable.light_on));
                    tv_scan_light.setTextColor(getResources().getColor(R.color.colorPrimary));
                    isLightOn = true;
                } else {
                    iv_scan_light.setImageDrawable(getResources().getDrawable(R.drawable.light_off));
                    tv_scan_light.setTextColor(getResources().getColor(R.color.white));
                    isLightOn = false;
                }
            }
        });
        lin_scan_input = (LinearLayout) findViewById(R.id.lin_scan_input);
        lin_scan_input.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_scan_light.setTextColor(getResources().getColor(R.color.white));
                isLightOn = false;
                finish();
            }
        });
    }


    @Override
    public void onBackPressed() {
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        cameraManager = new CameraManager(getApplication());
        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        viewfinderView.setCameraManager(cameraManager);
        handler = null;
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
        }

        beepManager.updatePrefs();
        inactivityTimer.onResume();
        source = IntentSource.NONE;
        decodeFormats = null;
        characterSet = null;
    }

    @Override
    protected void onPause() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }

        inactivityTimer.onPause();
        beepManager.close();
        cameraManager.closeDriver();
        if (!hasSurface) {
            SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
            SurfaceHolder surfaceHolder = surfaceView.getHolder();
            surfaceHolder.removeCallback(this);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            this.holder = holder;
            startCamera(holder);


        }
    }

    private void startCamera(SurfaceHolder holder) {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
                        Constants.READ_LOCATION_PERMISSION_REQUEST);
            } else {
                initCamera(holder);
            }
        } else {
            initCamera(holder);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        //确保是我们的请求
        if (requestCode == Constants.READ_LOCATION_PERMISSION_REQUEST) {
            if (grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initCamera(holder);
            } else if (grantResults.length == 2 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                final InCarDialog inCarDialog = new InCarDialog(CaptureActivity.this);
                inCarDialog.setTitle(getString(R.string.dialogTitle));
                inCarDialog.setMessage("您已拒绝相机权限");
                inCarDialog.setYesOnclickListener("确定", new InCarDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        startCamera(holder);
                    }
                });
                inCarDialog.setNoOnclickListener("取消", new InCarDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        inCarDialog.dismiss();
                    }
                });
                inCarDialog.setCancelable(false);
                inCarDialog.show();

            } else if (grantResults.length == 2 && grantResults[1] == PackageManager.PERMISSION_GRANTED) {

            } else {
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
    }

    /**
     * 扫描成功，处理反馈信息
     *
     * @param rawResult
     * @param barcode
     * @param scaleFactor
     */
    public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) {
        inactivityTimer.onActivity();

        boolean fromLiveScan = barcode != null;
        //这里处理解码完成后的结果，此处将参数回传到Activity处理
        if (fromLiveScan) {
            beepManager.playBeepSoundAndVibrate();
            Intent intent = getIntent();
            intent.putExtra("codedContent", rawResult.getText());
            intent.putExtra("codedBitmap", barcode);
            setResult(Constants.RESULT_SCAN, intent);
            finish();
        }
    }

    /**
     * 初始化Camera
     *
     * @param surfaceHolder
     */
    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            return;
        }
        try {
            // 打开Camera硬件设备
            cameraManager.openDriver(surfaceHolder);
            // 创建一个handler来打开预览，并抛出一个运行时异常
            if (handler == null) {
                handler = new CaptureActivityHandler(this, decodeFormats,
                        decodeHints, characterSet, cameraManager);
            }
        } catch (IOException ioe) {
            Log.w(TAG, ioe);
            displayFrameworkBugMessageAndExit();
        } catch (RuntimeException e) {
            Log.w(TAG, "Unexpected error initializing camera", e);
            displayFrameworkBugMessageAndExit();
        }
    }

    /**
     * 显示底层错误信息并退出应用
     */
    private void displayFrameworkBugMessageAndExit() {
        final InCarDialog inCarDialog = new InCarDialog(this);
        inCarDialog.setTitle(getString(R.string.dialogTitle));
        inCarDialog.setMessage("您已拒绝使用相机");
        inCarDialog.setYesOnclickListener("确定", new InCarDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                inCarDialog.dismiss();
            }
        });
        inCarDialog.setNoOnclickListener("取消", new InCarDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                inCarDialog.dismiss();
            }
        });
        inCarDialog.setCancelable(false);
        inCarDialog.show();
    }


}
